package indicators

import (
	"fmt"
	"sort"

	"gitee.com/lyuanbo/stock-trade/internal/pkg/mathx"
	"gitee.com/lyuanbo/stock-trade/internal/pkg/mq"
	"gitee.com/lyuanbo/stock-trade/internal/pkg/stock/constant"
	"github.com/duke-git/lancet/v2/slice"
)

func init() {
	// 注册均线指标
	indicators = append(indicators, "MA")
	//Register("MA", &Ma{})
}

// Ma 均线
type Ma struct{}

func (m *Ma) Name() string { return "MA" }

func (m *Ma) Run() {
	// 监听实时行情
	_ = mq.Default().Subscribe(constant.MqTopicTypeRealtime, m.Name(), func(symbol string, kline *constant.Kline) {
		fmt.Println("ma:", symbol, kline)

		// 计算各个
	})
}

// MA 均线计算
func MA(klines []constant.Kline, ma []int) (values []map[int]float64) {
	// 若 klines 为空, 则返回空值
	if len(klines) == 0 {
		return nil
	}

	// 当 ma 为 nil 时,需要对数据分时线
	if ma == nil {
		ma = append(ma, -1)
	}

	// 去重
	ma = slice.Unique(ma)
	// 排序
	sort.Ints(ma)

	// 存储均线的值
	maVal := make(map[int]float64)

	for i, line := range klines {
		lineMa := make(map[int]float64, len(ma))
		for _, num := range ma {
			// 累加
			maVal[num] += line.Close
			// 过滤 -1, 若k线长度小于均线，则只累加
			if num != -1 && i-num+1 < 0 {
				continue
			}

			// 过滤 -1, 大于均线的 k 线才需要计算
			if num != -1 && i-num+1 > 0 {
				// 计算移除的 k 线
				index := 0
				if i-num > 0 {
					index = i - num
				}

				maVal[num] = maVal[num] - klines[index].Close
			}

			// 若 num = -1, 则直接处于当前 k线的索引
			dividend := num
			if num == -1 {
				dividend = i + 1
			}

			lineMa[num] = mathx.Round(maVal[num]/float64(dividend), line.Stock.Precision)
		}

		values = append(values, lineMa)
	}

	return values
}
